import { useState, useEffect } from 'react'
import { Table, Button, Modal, Form, Input, message, Popconfirm, Space } from 'antd'
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'

interface UserType {
  id: string
  username: string
  email: string
  phone: string
  role: string
}

export default function UserManagement() {
  const [users, setUsers] = useState<UserType[]>([])
  const [loading, setLoading] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [currentUser, setCurrentUser] = useState<UserType | null>(null)
  const [form] = Form.useForm()
  const [searchText, setSearchText] = useState('')

  // 模拟从API获取用户数据
  useEffect(() => {
    fetchUsers()
  }, [])

  const fetchUsers = () => {
    setLoading(true)
    // 这里应该是API调用，我们使用模拟数据
    setTimeout(() => {
      const mockUsers: UserType[] = [
        { id: '1', username: 'admin', email: 'admin@example.com', phone: '13800138000', role: '管理员' },
        { id: '2', username: 'user1', email: 'user1@example.com', phone: '13900139000', role: '编辑' },
        { id: '3', username: 'user2', email: 'user2@example.com', phone: '13700137000', role: '查看' },
      ]
      setUsers(mockUsers)
      setLoading(false)
    }, 500)
  }

  // 过滤用户数据
  const filteredUsers = users.filter(user =>
    user.username.toLowerCase().includes(searchText.toLowerCase()) ||
    user.email.toLowerCase().includes(searchText.toLowerCase()) ||
    user.phone.includes(searchText)
  )

  const handleAdd = () => {
    setCurrentUser(null)
    form.resetFields()
    setIsModalOpen(true)
  }

  const handleEdit = (user: UserType) => {
    setCurrentUser(user)
    form.setFieldsValue(user)
    setIsModalOpen(true)
  }

  const handleDelete = (id: string) => {
    // 这里应该是API调用
    setUsers(users.filter(user => user.id !== id))
    message.success('用户删除成功')
  }

  const handleSubmit = () => {
    form.validateFields().then(values => {
      if (currentUser) {
        // 更新用户
        setUsers(users.map(user => 
          user.id === currentUser.id ? { ...user, ...values } : user
        ))
        message.success('用户更新成功')
      } else {
        // 添加用户
        const newUser = { ...values, id: Date.now().toString() }
        setUsers([...users, newUser])
        message.success('用户添加成功')
      }
      setIsModalOpen(false)
    })
  }

  const columns: ColumnsType<UserType> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <h2>用户管理</h2>
        <Space>
          <Input
            placeholder="搜索用户"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加用户
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={filteredUsers}
        rowKey="id"
        loading={loading}
        bordered
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={currentUser ? '编辑用户' : '添加用户'}
        open={isModalOpen}
        onOk={handleSubmit}
        onCancel={() => setIsModalOpen(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Input placeholder="请输入角色" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}